from django.http import JsonResponse
from django.views import View
from users.models import User
from django_redis import get_redis_connection
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from users.serializers.register_serializers import UserRegisterModelSerializer
import logging, random

logger = logging.getLogger('django')
import re



# 获取短信验证码
class SMS_Veri_Code(View):

    def get(self, request, mobile):

        # 创建redis对象
        redis_conn = get_redis_connection('verify_code')

        # 进入函数后, 先获取存储在 redis 中的数据
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        # 查看数据是否存在, 如果存在, 说明60s没过, 返回
        if send_flag:
            return JsonResponse({'code': 400,
                                 'errmsg': '发送短信过于频繁'})
        # 将这句话提到前面最开始的位置:
        redis_conn = get_redis_connection('verify_code')

        # 进入函数后, 先获取存储在 redis 中的数据
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        # 查看数据是否存在, 如果存在, 说明60s没过, 返回
        if send_flag:
            return JsonResponse({'code': 400,
                                 'errmsg': '发送短信过于频繁'})
        # 验证参数
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'success': False,
                                 'errmsg': 'mobile格式有误'})

        # 生成验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        print('yz', sms_code)

        # 使用pipeline 降低往返时间的延迟
        # 创建管道对象:
        pl = redis_conn.pipeline()

        # 存储验证码
        # redis_conn.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('sms_%s' % mobile, 300, sms_code)

        redis_conn.setex('send_flag_%s' % mobile, 60, 1)
        pl.setex('send_flag_%s' % mobile, 60, 1)

        pl.execute()

        # 返回数据
        return JsonResponse({'message': 'OK',
                             'sms_code': sms_code,
                             'success': True})


# 用户注册
class UserRegisterModelViewSet(ModelViewSet):
    queryset = User.objects.all()

    serializer_class = UserRegisterModelSerializer

    def get_queryset(self):
        # 获取前端传递的keyword值
        keyword = self.request.query_params.get('keyword')
        # 如果keyword是空字符，则说明要获取所有用户数据
        if keyword is '' or keyword is None:
            return User.objects.all()
        else:
            return User.objects.filter(username=keyword)

    def get(self, request):

        data = self.queryset
        serializer = self.get_serializer(data=data, many=True)

        return Response(serializer.data)

    # 重写create
    def create(self, request, *args, **kwargs):

        sms_code_client = request.data.pop('sms_code')
        mobile = self.request.data['mobile']

        # 链接redis
        redis_conn = get_redis_connection('verify_code')

        # 从 redis中，获取保存的短信验证码
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        # 判断该值是否存在
        if not sms_code_server:
            return JsonResponse({'code': 400,
                                 'errmsg': '短信验证码过期'})

        # 把redis中取得值和前端发的值对比
        if sms_code_client != sms_code_server.decode():
            return JsonResponse({'code': 400,
                                 'errmsg': '验证码有误'})

        data = super().create(request, *args, **kwargs)

        return data
